package com.sanri.tools.modules.mock.l7.websocket.chat.repository;

import com.sanri.tools.modules.core.exception.ToolException;
import com.sanri.tools.modules.core.service.file.FileManager;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.ChatFatUser;
import com.sanri.tools.modules.mock.l7.websocket.chat.domain.ChatUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * $datadir
 *   chat
 *     users
 *       $username 用户配置
 *         info
 *         contacts[Dir]
 *          $loginName[File]
 *         groups[Dir]
 *          $groupId[File]
 */
@Repository
@Slf4j
public class ChatUserRepository {

    @Autowired
    private FileManager fileManager;

    @Autowired
    private MessageRepository messageRepository;

    /**
     * 用户列表
     * @return
     */
    public Set<String> users(){
        File chat = fileManager.mkDataDir("chat/users/");
        return Arrays.stream(chat.list()).collect(Collectors.toSet());
    }

    /**
     * 添加用户
     * @param username
     * @param password
     * @throws IOException
     */
    public void openChat(String username) throws IOException {
        File userDir = userDir(username);

        new File(userDir,"info").createNewFile();

        new File(userDir,"contacts").mkdirs();

        new File(userDir,"groups").mkdirs();
    }

    /**
     * 删除用户
     * @param username
     */
    public void del(String username){
        File userDir = userDir(username);
        userDir.delete();
    }

    public static final String avatar = "avatar:";
    public static final String displayName = "displayName:";

    public ChatUser userSimpleInfo(String username) throws IOException {
        File userDir = userDir(username);
        final File infoFile = new File(userDir, "info");
        ChatUser chatUser = new ChatUser(username);
        if (infoFile.exists()){
            List<String> lines = FileUtils.readLines(infoFile, StandardCharsets.UTF_8);

            if (CollectionUtils.isNotEmpty(lines)){
                for (String line : lines) {
                    if (line.startsWith(avatar)){
                        chatUser.setAvatar(line.substring(avatar.length()));
                    }
                    if (line.startsWith(displayName)){
                        chatUser.setDisplayName(line.substring(displayName.length()));
                    }
                }
            }
        }

        return chatUser;
    }

    /**
     * 用户信息详情
     * @param username
     * @return
     * @throws IOException
     */
    public ChatFatUser userInfo(String username) throws IOException {
        ChatUser chatUser = userSimpleInfo(username);
        ChatFatUser chatFatUser = new ChatFatUser(chatUser);
        return chatFatUser;
    }

    /**
     * 密码匹配
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    public boolean matchPassword(String username, String password) throws IOException {
        File userDir = userDir(username);
        String realPassword = FileUtils.readFileToString(new File(userDir, "password"), StandardCharsets.UTF_8);

        return realPassword.equals(password);
    }

    /**
     * 添加联系人
     */
    public void addContact(String username, String contact) throws IOException {
        Set<String> users = users();
        if (!users.contains(contact)){
            throw new ToolException("联系人 "+ contact+ " 不存在, 添加失败");
        }

        // 添加联系人为双向添加
        File contactFile = contactFile(username, contact);
        if (contactFile.exists()){
            throw new ToolException("联系人 "+ contact+ " 已经存在, 不要重复添加");
        }
        contactFile.createNewFile();

        // 另一边也要添加联系人
        File reverseContactFile = contactFile(contact, username);
        reverseContactFile.createNewFile();
    }

    /**
     * 删除联系人
     * @param username
     * @param contact
     */
    public void delContact(String username, String contact){
        File file = contactFile(username, contact);
        if (file.exists()){
            file.delete();
        }

        File file1 = contactFile(contact, username);
        if (file1.exists()){
            file1.delete();
        }
    }

    /**
     * 用户目录
     * @param username
     * @return
     */
    public File userDir(String username){
        File chat = fileManager.mkDataDir("chat/users/"+ username);
        return chat;
    }

    /**
     * 联系人文件 $username/contacts/$contact
     * @param username
     * @param contact 联系人
     * @return
     */
    public File contactFile(String username, String contact){
        File userDir = userDir(username);
        File contacts = new File(userDir, "contacts");
        contacts.mkdirs();
        return new File(contacts, contact);
    }

    public String[] listContacts(String username) {
        File userDir = userDir(username);
        String[] contacts = new File(userDir, "contacts").list();
        return contacts;
    }
}
